<template>
  <div :class="containerClass">
    <template v-for="(item, index) in appList" :key="item.id">
      <div class="relative p-2 rounded-lg overflow-hidden hover:shadow-md hover:shadow-black/20 transition-all duration-300">
        <!-- 收藏按钮 - 只在客户端且有favorite对象时显示 -->
        <svg-icon v-if="isClient && favorite" :name="favorite.isMarkapp(item) ? 'mark-black' : 'mark'" class="absolute top-1 right-1 cursor-pointer" @click="favorite.isMarkapp(item) ? favorite.removeMarkapp(item) : favorite.handleMarkapp(item)" />
        
        <!-- 应用链接 -->
        <a :href="getItemUrl(item.name)" @click="handleClick(item)">
          <!-- 应用信息头部 -->
          <div class="flex items-center gap-2 mb-3 mr-6">
            <img :src="item.icon" :alt="item.name" class="w-16 h-16 rounded-lg" loading="lazy">
            <div class="flex flex-col gap-1">
              <div class="flex items-center gap-1">
                <div class="text-sm font-bold line-clamp-1">{{ item.name }}</div>
                <div v-if="item.ifChoice" class="text-xs text-white bg-primary rounded-sm px-1.5 py-0.5 flex-shrink-0">
                  {{ item.ifChoice ? 'Editor\'s Choice' : '' }}
                </div>
              </div>
              <div v-if="layout === 'vertical'" class="text-xs text-gray-500 line-clamp-3" v-html="item.desc || 'No description'" />
              <div v-else class="text-xs text-gray-500 line-clamp-3 v-html" v-html="item.desc || 'No description'" />
            </div>
          </div>
          
          <!-- 应用大图 -->
           <div class="relative">
             <img :src="item.bigIcon" :alt="item.name" class="w-full h-auto rounded-sm object-cover object-center" loading="lazy" style="aspect-ratio: 3/2;">
            <div class="absolute top-0 right-0 text-white bg-gray-200/20 rounded-sm px-2 py-0.5">{{ item.cost }}</div>
           </div>
        </a>
        
        <!-- 分类标签 -->
        <div class="flex gap-3 mt-2 flex-wrap">
          <div v-for="(category, index) in item.secondCategory" :key="index" class="text-xs text-blue-500">{{ category }}</div>
        </div>
      </div>
      
      <!-- 在第二个app后面插入广告 -->
      <AdsGoogleAdCollect v-if="isMobile && index === 1 && adSlot === 'mainDisplay1'" slot-type="mainDisplay1" />
      <AdsGoogleAdCollect v-if="index === 0 && adSlot === 'detailDisplay2'" slot-type="detailDisplay2" />
    </template>
  </div>
</template>

<script setup>
const props = defineProps({
  appList: {
    type: Array,
    default: () => []
  },
  selectedMainCategoryName: {
    type: String,
    default: ''
  },
  selectedSubCategoryName: {
    type: String,
    default: ''
  },
  layout: {
    type: String,
    default: 'horizontal',
    validator: (value) => ['vertical', 'horizontal'].includes(value)
  },
  adSlot: {
    type: String,
    default: ''
  }
})

// 检测是否在客户端
const isClient = ref(false)

// 检测是否在移动端
const isMobile = ref(false)

// 响应式变量
const favorite = ref(null)
const urlParams = ref(null)
const appUrl = ref(new Map())
const handleClick = (item) => {
  logEvent('Click_App', {
    tag: `${props.selectedMainCategoryName}/${props.selectedSubCategoryName}/${item.cost}`,
    App: item.name
  })
}
// 计算容器样式类
const containerClass = computed(() => {
  return props.layout === 'vertical' 
    ? 'flex flex-col gap-3'
    : 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-3'
})

// 生成app详情url
const getAppDetailUrl = (item) => {
  // 统一URL生成逻辑，避免服务端和客户端不一致
  const category = props.selectedMainCategoryName || (item.category && item.category.length > 0 ? item.category[0].replace('#', '') : '')
  const subCategory = props.selectedSubCategoryName || (item.secondCategory && item.secondCategory.length > 0 ? item.secondCategory[0].replace('#', '') : '')
  
  // 在服务端时，urlParams可能不可用，直接构建URL
  if (!isClient.value || !urlParams.value) {
    const queryParams = new URLSearchParams()
    if (category) queryParams.set('category', category)
    if (subCategory) queryParams.set('subCategory', subCategory)
    if (item.name) queryParams.set('app', item.name)
    return `/detail?${queryParams.toString()}`
  }
  
  // 客户端时，使用urlParams构建URL
  const queryParams = {
    ...urlParams.value.getHomeParams(),
    category: category,
    subCategory: subCategory,
    app: item.name
  }
  return `/detail?${urlParams.value.buildQueryString(queryParams)}`
}

// 安全地获取应用详情页URL
const getItemUrl = (itemName) => {
  // 优先从appUrl Map中获取
  if (appUrl.value.has(itemName)) {
    return appUrl.value.get(itemName)
  }
  
  // 如果Map中没有，则生成一个基本的URL
  // 修复水合问题：服务端和客户端都应该使用相同的URL生成逻辑
  const item = props.appList.find(app => app.name === itemName)
  if (item) {
    return getAppDetailUrl(item)
  }
  
  // 兜底方案
  return `/detail?app=${itemName}`
}

// 在客户端挂载后初始化composables
onMounted(() => {
  isClient.value = true
  isMobile.value = window.innerWidth < 768
  
  // 只在客户端执行这些composables
  favorite.value = useFavorite()
  urlParams.value = useUrlParams()
  favorite.value.initFavoriteList()
  
  // 初始化应用URL映射
  updateAppUrl()
})

// 更新应用URL映射
const updateAppUrl = () => {
  if (!isClient.value || !urlParams.value) return
  
  const url = new Map()
  // 添加安全检查，确保appList存在且是数组
  if (props.appList && Array.isArray(props.appList)) {
    props.appList.forEach(item => {
      if (item && item.name) {
        url.set(item.name, getAppDetailUrl(item))
      }
    })
  }
  appUrl.value = url
}

// 监听appList变化，更新URL映射
watch(() => props.appList, () => {
  if (isClient.value) {
    updateAppUrl()
  }
}, { deep: true })

// 在服务端时，预先计算一些基本的URL
onServerPrefetch(() => {
  const url = new Map()
  if (props.appList && Array.isArray(props.appList)) {
    props.appList.forEach(item => {
      if (item && item.name) {
        url.set(item.name, getAppDetailUrl(item))
      }
    })
  }
  appUrl.value = url
})
</script>

<style scoped>
.bg-primary {
  background-color: var(--primary-color);
}

:deep(.mark-down-keyword) {
  color: var(--primary-color);
  font-weight: bold;
}

/* 当使用v-html时的样式 */
.v-html {
  /* 可以添加额外的v-html样式 */
}
</style>